bigint.ts ➔ primes   C
last analyzed

Complexity

Conditions 9

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 9

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 6.6666
c 0
b 0
f 0
cc 9
crap 9
1
/**
2
 * Find the greatest common denominator of the two numbers.
3
 */
4 6
export const gcd = (a: bigint, b: bigint): bigint => {
5 374
  if (b === 1n || a === 1n) {
6 175
    return 1n
7
  }
8 199
  while (b !== 0n) {
9
    //[a, b] = [b, a % b] // not pretty???
10 761
    const t = a % b
11 761
    a = b
12 761
    b = t
13
  }
14 199
  return a < 0n ? -a : a
15
}
16
17
/**
18
 * Returns true if the number is prime.
19
 */
20 6
export const isPrime = (n: bigint): boolean => {
21 20785
  if (n === 1n) return false
22 20784
  for (let i = 2n; i * i <= n; i++) {
23 295866
    if (n % i === 0n) return false
24
  }
25 2459
  return true
26
}
27
28
/**
29
 * Yields the prime numbers.
30
 */
31 6
export function* primes(): Generator<bigint> {
32 13
  for (let n = 2n; true; n++) {
33 20779
    if (isPrime(n)) {
34 2456
      yield n
35
    }
36
  }
37
}
38
39
/**
40
 * Finds the prime factors, returning them in ascending order as arrays with their exponent as the second element.
41
 */
42 6
export const primeFactors = (n: bigint): Array<[bigint, bigint]> => {
43 12
  const f: Array<[bigint, bigint]> = []
44 12
  for (const p of primes()) {
45 2451
    let e = 0n
46 2451
    while (n % p === 0n) {
47 40
      e++
48 40
      n /= p
49
    }
50 2451
    if (e) f.push([p, e])
51 2451
    if (n === 1n) break
52
  }
53 12
  return f
54
}
55